<?php
namespace app\api\controller;
use app\common\controller\ApiBase;
use app\common\library\ErrorType;
use app\common\model\User;
use think\Db;
use think\facade\Cache;

/**
 * @title Register
 * @description 用户注册相关类
 * @package app\api\controller
 */
class Register extends ApiBase
{
    /**
     * @title 邮箱检查
     * @description 检查邮箱是否已经注册过了
     * @author Admin ldy
     * @url /api/register/checkMailExist
     * @param name:email  type:string require:1 default:1 desc:邮箱必填
     * @time 2018/9/18  9:24
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkMailExist(){
        $email = $this->request->param('email');
        $data = [
            'email' => $email,
        ];
        $validate = new \app\common\validate\User;
        if (!$validate->scene('checkMailExist')->check($data)) {
            $this->error($validate->getError());
        }
        $hasEmail = Db::name('User')->where(['email'=>$email])->find();
        if ($hasEmail){
            $this->error('邮箱已存在','',1003);
        }else{
            $this->success('恭喜您，该邮箱可以使用','',200);
        }
    }

    /**
     * @title 邮箱&手机号 注册
     * @description 通用注册，手机号、邮箱、邀请码、密码，可以注册平台，注册后再验证邮箱、手机号
     * @author Admin ldy
     * @url /api/register/registerByMail
     * @param name:email  type:string require:1 default:1 desc:邮箱必填
     * @param name:mobile  type:string require:1 default:1 desc:手机号必填
     * @param name:invite_code  type:string require:1 default:1 desc:邀请码必填
     * @param name:pwd  type:string require:1 default:1 desc:密码必填
     * @param name:isCheckEmail  type:int require:1 default:1 desc:邮箱是否已经验证必填
     * @time 2018/9/18  9:26
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function registerByMail(){
        $email = $this->request->param('email');
        $mobile = $this->request->param('mobile');
        $invite_code = $this->request->param('invite_code');
        $password = $this->request->param('pwd');
        $isCheckEmail = $this->request->param('isCheckEmail');
        if (empty($isCheckEmail)){
            //设定默认值
            $isCheckEmail = 0;
        }
        $data = [
            'mobile'  => $mobile,
            'email' => $email,
            'invite_code'=>$invite_code,
            'password'=>$password,
            'isCheckEmail'=>$isCheckEmail
        ];
        $validate = new \app\common\validate\User;
        if (!$validate->scene('emailRegister')->check($data)) {
            $this->error($validate->getError());
        }

        $hasEmail = Db::name('User')->where(['email'=>$email,'mobile'=>$mobile])->find();
        if ($hasEmail){
            $this->error("该邮箱已注册过了，请直接登录！",'',1001);
        }

        if ($invite_code != 'kkou88'){
            $this->error('邀请码错误！请联系管理员');
        }

//        $data['email']=$email;
//        $data['mobile']=$mobile;
//        $data['invite_code']=$invite_code;
//        $re = Db::name('User')->insert($data);
//        $user = new \app\common\model\User;
        $user = new User();
        $user->mobile = $mobile;
        $user->email = $email;
        $user ->invite_code = $invite_code;
        $user->password = md5($password);
        $user->is_check_email = $isCheckEmail;
        $user->nickname = '藏'.substr(md5($email), 1, 10);

        Db::startTrans();
        try
        {
            $re = $user->save();
            Db::commit();
            if ($re){
                $token = \yu\Random::uuid_yu();
                //token设置有效期为30天
                \cache($token,$user->id,60*60*24*30,'login-token');
                $result = array(
                    'token'=>$token,
                    'user'=>$user,
                );
                //异步发送成功消息
                $content = '您于 '.Date('Y-m-d').' 注册收藏家平台成功！获得赠送积分50！获得经验100！请注意查收！';
                $re1 = sendMsgToUser($user->id,'注册收藏家成功！',$content);
                //异步发送积分
                $re2 = sendScoreTo($user->id,50);
                //异步发送经验值
                $re3 = sendExpTo($user->id,100);
                $tre = array(
                    'r1'=>$re1->getMsg(),
                    'r2'=>$re2->getMsg(),
                    'r3'=>$re3->getMsg(),
                );
                $result['re'] = $tre;

                $this->success('恭喜你，注册成功！',$result,200);
            }else{
                $this->error('注册失败！请联系管理人员');
            }
            //注册成功的事件
            Hook::listen("user_register_successed", $this->_user);
        }
        catch (Exception $e)
        {
            $this->error('注册失败！请联系管理人员',$e->getMessage());
            Db::rollback();
        }
    }

    /**
     * @title 发送邮箱验证码
     * @description 发送邮箱验证码，10分钟内有效，可以验证绑定邮箱
     * @author Admin ldy
     * @url /api/register/sendEmailCode
     * @param name:email  type:string require:1 default:1 desc:
     * @time 2018/9/18  10:18
     */
    public function sendEmailCode(){
        $email = $this->request->param('email');
        $data = [
            'email' => $email,
        ];
        $validate = new \app\common\validate\User;
        if (!$validate->scene('sendEmailCode')->check($data)) {
            $this->error($validate->getError());
        }
        $cacheid = md5($email);
        $isCodeAlreadyExit = Cache::get($cacheid);
        if ($isCodeAlreadyExit){
            $this->success('发送成功，请使用！',$isCodeAlreadyExit,200);
        }
        $code = rand(100000,999999);
        Cache::set($cacheid,$code,10*60);
        $title='收藏家的验证码';
        $content='<br>收藏家验证码为：'.$code.'<br>请于10分钟内使用。<br>如有疑问请回复邮件至yubenziyou@qq.com联系我们<br>';
        $status= $this->sendEmail($email,$title,$content);
        //简单的判断与提示信息
        if ($status) {
            $this->success('发送成功',$code,200);
        }else{
            $this->err(ErrorType::ACTION_FAILED);
        }
    }

    /**
     * @title 验证邮箱验证码，绑定邮箱
     * @description 验证邮箱验证码，绑定邮箱
     * @author Admin ldy
     * @url /api/register/checkEmailCode
     * @param name:email  type:string require:1 default:1 desc: 验证的邮箱
     * @param name:code  type:string require:1 default:1 desc: 验证码字符串
     * @time 2018/9/18  11:21
     */
    public function checkEmailCode(){
        $email = $this->request->param('email');
        $code = $this->request->param('code');
        $data = [
            'email' => $email,
            'code'=>$code,
        ];
        $validate = new \app\common\validate\User;
        if (!$validate->scene('checkEmailCode')->check($data)) {
            $this->error($validate->getError());
        }
        $cacheid = md5($email);
        $saveCode = Cache::get($cacheid);
        if (!$saveCode){
            $this->error('验证码已过期！');
        }
        if ($saveCode == $code){
            Cache::set($cacheid,null);
            //这里做一些操作，邮箱已验证，应该修改用户邮箱已验证标记
            //这里用户做了一些操作，应该奖励一些积分
            $this->success('验证成功');
        }else{
            $this->error("验证失败！");
        }

    }



    /**
     * @title 重置密码
     * @description 忘记密码的时候，调用这个接口，可以重置密码
     * @author Admin ldy
     * @url /api/register/resetPassword
     * @param name:email  type:string require:1 default:1 desc:邮箱必填
     * @param name:code  type:string require:1 default:1 desc:验证码必填
     * @param name:pwd  type:string require:1 default:1 desc:重置之后的密码
     * @time 2018/9/18  12:33
     */
    public function resetPassword(){
        $email = $this->request->param('email');
        $code = $this->request->param('code');
        $password = $this->request->param('pwd');
        $data = [
            'email' => $email,
            'code'  => $code,
            'password'=>$password,
        ];
        $validate = new \app\common\validate\User;
        if (!$validate->scene('resetPassword')->check($data)) {
            $this->error($validate->getError());
        }
        $cacheid = md5($email);
        $saveCode = Cache::get($cacheid);
        if (!$saveCode){
            $this->error('验证码已过期！');
        }
        if ($saveCode == $code){
            //这里用户做了一些操作，应该奖励一些积分
            $user = \app\common\model\User::getByEmail($email);
            if (!user){
                $this->error('用户信息有误！');
            }
            $user -> password = md5($password);
            $re = $user ->save();
            if ($re){

                $this->success('您已成功重置密码，请牢记您的密码！');
            }else{
                $this->err(ErrorType::ACTION_FAILED);
            }

        }else{
            $this->error("验证失败！");
        }
    }






}
